package persistencia;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import negocio.Servico;

public class MyMODAO extends ConexaoMySQLDAO {

    private PreparedStatement stIncluir;
    private PreparedStatement stPesquisaCodigo;
    private PreparedStatement stPesquisaNome;
    private PreparedStatement stListar;
    private PreparedStatement stAtualiza;
    private final Connection con;

    public MyMODAO() throws IOException, SQLException {
        con = super.getConexao();
        stIncluir = con.prepareStatement(
                "INSERT INTO cadmo (descricao, valorservico) VALUES (?, ?)");
        stListar = con.prepareStatement(
                "SELECT * FROM cadmo");
        stPesquisaCodigo = con.prepareStatement(
                "SELECT * FROM cadmo WHERE id_mo=?");
        stPesquisaNome = con.prepareStatement(
                "SELECT * FROM cadmo WHERE nome LIKE ?");
        stAtualiza = con.prepareStatement(
                "UPDATE cadmo SET descricao=?, valorservico=? WHERE id_mo=?");
    }

    public void adiciona(Servico umaMO) throws Exception {
        stIncluir.setString(1, umaMO.getDesc());
        stIncluir.setInt(2, umaMO.getValorInt());
        stIncluir.executeQuery();
    }

    public List<Servico> getMO() throws Exception {
        List<Servico> tmp = new ArrayList<Servico>();
        ResultSet rs = stListar.executeQuery();
        while (rs.next()) {
            tmp.add(new Servico(rs.getString("id_mo"), rs.getString("descricao"), rs.getInt("valorservico")));
        }
        return tmp;
    }

    public void altera(Servico novaMO) throws Exception {
        stAtualiza.setString(1, novaMO.getDesc());
        stAtualiza.setInt(2, novaMO.getValorInt());
        stAtualiza.setInt(3, Integer.parseInt(novaMO.getId_mo()));
        stAtualiza.executeUpdate();
    }

    public List<Servico> procuraPorNome(String chave) throws Exception {
        stPesquisaNome.setString(1, chave + "%");
        return getLista(stPesquisaNome.executeQuery());
    }

    public Servico procuraPorCodigo(int codigo) throws Exception {
        stPesquisaCodigo.setInt(1, codigo);
        List<Servico> res = getLista(stPesquisaCodigo.executeQuery());
        if (res.isEmpty()) {
            throw new Exception("Registro não encontrado");
        }
        return res.get(0);
    }

    private List<Servico> getLista(ResultSet rs) throws Exception {
        List<Servico> tmp = new ArrayList<Servico>();
        while (rs.next()) {
            tmp.add(new Servico(
                    rs.getString("id_mo"), rs.getString("descricao"),
                    rs.getInt("valorservico")));
        }
        return tmp;
    }
}